import { useEffect, useState, useRef } from 'react'

const FetchData = () => {
  const [search, setSearch] = useState('redux')
  const [data, setData] = useState([])
  const [isempty, setIsempty] = useState('请输入数据')
  const [isLoading, setIsLoading] = useState(false)
  const [url, setUrl] = useState(
    'https://hn.algolia.com/api/v1/search?query=redux'
  )
  const mounted = useRef();
  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
      console.log('我挂在了')
    } else {
      setIsLoading(true)
      setIsempty("")
      try {
        setTimeout(() => {
          setData([111, 122])
          setIsLoading(false)        
        }, 2000);
      } catch (error) {
        setIsempty("出错了")
      }     
    }
  }, [url])



  return (
    <>
      <form
        onSubmit={(e) => {
          setUrl(`https://hn.algolia.com/api/v1/search?query=${search}`)
          e.preventDefault()
        }}
      >
        <input
          type="text"
          value={search}
          onChange={(event) => setSearch(event.target.value)}
        />
        <button type="submit">搜索</button>
      </form>
      {isempty}
      {isLoading ? (
        <div>Loading ...</div>
      ) : (
        <ul>
          {data.map((item, i) => (
            <li key={i}>
              <a href='#'>{item}</a>
            </li>
          ))}
        </ul>
      )}
    </>
  )
}

export default FetchData
